package zcatt.examples.jface.snippets;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;


/*
 * 简单的treeViewer
 */
public class Snippet017SimpleTreeViewer {
	
	public static class MyModel{
		public MyModel parent;
		public List<MyModel> children = new ArrayList<>();
		public String name;
		
		public MyModel(String name, MyModel parent)
		{
			this.name = name;
			this.parent = parent;
			if(parent != null)
				parent.children.add(this);
		}
		
		@Override
		public String toString() {
			return name;
		}				
	}
	
	public static class MyContentProvider implements ITreeContentProvider{

		@Override
		public Object[] getElements(Object inputElement) {			
			return getChildren(inputElement);
		}

		@Override
		public Object[] getChildren(Object parentElement) {			
			return ((MyModel)parentElement).children.toArray();
		}

		@Override
		public Object getParent(Object element) {			
			return ((MyModel)element).parent;
		}

		@Override
		public boolean hasChildren(Object element) {
			return ((MyModel)element).children.size() > 0;
		}
		
	}

	TreeViewer viewer;
	
	public Snippet017SimpleTreeViewer(Shell shell) {
		viewer = new TreeViewer(shell);
		viewer.setLabelProvider(new LabelProvider());
		viewer.setContentProvider(new MyContentProvider());
		
		//SWT方式创建column
		Tree t = viewer.getTree();
		TreeColumn col = new TreeColumn(t, SWT.NONE);
		col.setWidth(100);
		col.setText("value");
		t.setHeaderVisible(true);
		t.setHeaderBackground(new Color(100,200,200));
		t.setLinesVisible(true);
		
		//create model
		MyModel root = new MyModel("root", null);
		MyModel tmp;
		for(int i = 0; i< 10; i++)
		{
			tmp = new MyModel("item"+i, root);
			for(int j = 0; j < i; j++)
			{
				new MyModel("item"+i+"."+j, tmp);
			}
		}
		
		viewer.setInput(root);			
	}

	public static void main(String[] args) {
		Display display = new Display();
		Shell shell = new Shell(display);
		shell.setLayout(new FillLayout());
		shell.setText("snippet017");
		new Snippet017SimpleTreeViewer(shell);
		shell.open();
		
		while(!shell.isDisposed())
		{
			if(!display.readAndDispatch())
				display.sleep();
		}
		
		display.dispose();

	}

}
